package com.bestcem.xm.member.handler.member;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.AppRequestErrorCode;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.member.controller.param.HttpCreateMemberParam;
import com.bestcem.xm.member.controller.param.HttpUpdateHttpMemberParam;
import com.bestcem.xm.member.dao.MemberDao;
import com.bestcem.xm.member.entity.mysql.SourceCardDo;
import com.bestcem.xm.member.entity.pojo.MemberDO;
import com.bestcem.xm.member.enums.CardSourceTypeEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.enums.NewMemberStatusEnum;
import com.bestcem.xm.member.mq.message.MemberMessage;
import com.bestcem.xm.member.service.dto.OrganizationDTO;
import com.bestcem.xm.member.util.MemberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;


/**
 * 机构联系人
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/16
 */
@Slf4j
@Component
public class InstitutionMemberHandler extends BaseMemberHandle {

    @Resource
    private MemberDao memberDao;

    @Override
    public ServiceResult<String> checkParams(HttpCreateMemberParam param) {
        String email = param.getEmail();
        String mobile = param.getMobile();
        String outNo = param.getOutNo();
        if (StrUtil.isEmpty(email) && StrUtil.isEmpty(mobile) && StrUtil.isEmpty(outNo)) {
            return ServiceResult.fail("手机号，邮箱和外部编号至少填写一个");
        }

        // 机构联系人 机构名称不能为空 并且机构 名称不能重复
        String instituteName = param.getInstituteName();
        if (StrUtil.isEmpty(instituteName)) {
            return ServiceResult.fail("机构名称不能为空");
        }
        Integer count = memberDao.countByOrgIdAndInstituteNameAndNotEqualStatus(param.getOrgId(), param.getInstituteName(), 4);
        if (count > 0) {
            return ServiceResult.fail("机构名称已存在");
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<String> save(HttpCreateMemberParam param) {
        // 对指定参数进行校验
        ServiceResult<String> checkParamsResult = checkParams(param);

        if (!checkParamsResult.isSuccess()) {
            return ServiceResult.<String>fail(checkParamsResult.getMsg())
                    .setErrorCode(String.valueOf(AppRequestErrorCode.PARAM_LOST));
        }
        // 校验姓名
        String name = param.getName();
        if (StringUtils.hasText(name) && name.length() > 50) {
            return ServiceResult.<String>fail("机构对接人长度不能超过50")
                    .setErrorCode(String.valueOf(AppRequestErrorCode.PARAM_RANGE));
        }
        // 检查一下数据的重复性
        ServiceResult<String> checkMobileAndEmailResult = checkUniqueValue(param.getMobile(), param.getEmail(), param.getMemberType(), param.getOrgId(), param.getOutNo());
        if (!checkMobileAndEmailResult.isSuccess()) {
            return ServiceResult.<String>fail(checkMobileAndEmailResult.getData(), checkMobileAndEmailResult.getMsg())
                    .setErrorCode(checkMobileAndEmailResult.getErrorCode());
        }
        //获取序号
        String memberNo = getMemberNo(param.getOrgId(), param.getMemberType());

        // 创建联系人
        MemberDO member = MemberUtil.httpMemberBaseParamToMemberDo(param);
        member.setMemberNo(memberNo);
        member.setStatus(NewMemberStatusEnum.MEMBER_STATUS_ACTIVATED.getIndex());
        member.setSource("manual");
        member = memberDao.manualSave(member);
        // 获取组织信息
        ServiceResult<OrganizationDTO> organization = getOrganization(param.getOrgId());
        if (!organization.isSuccess()) {
            return ServiceResult.<String>fail(organization.getMsg())
                    .setErrorCode("-1");
        }
        //若 手机或者邮箱是内部联系人
        String identityType = "企业对接人";
        OrganizationDTO dto = organization.getData();

        // 推送创建的联系人
        MemberMessage message = MemberUtil.memberDoToMemberMessage(member);
        message.setIdentityType(identityType);
        message.setOrgName(dto.getName());
        message.setOrgCode(dto.getCode());
        message.setNumberId("000");
        memberUtil.publishCreateMember(message);
        return ServiceResult.success(member.getId());
    }

    @Override
    public XmResultJson<String> updateManualMember(MemberDO member, HttpUpdateHttpMemberParam param) {
        // 用户手机号，微信userid,支付宝userid,邮箱不能同时为空

        // 对 email， mobile， openid， alipay_user_id 进行校验
        ServiceResult<String> checkResult = checkUpdateParam(member, param);
        if (!checkResult.isSuccess()) {
            return XmResultJson.fail(Integer.valueOf(checkResult.getErrorCode()), checkResult.getMsg());
        }

        // 校验机构对接人
        String name = param.getName();
        if (StringUtils.hasText(name) && name.length() > 50) {
            return XmResultJson.fail(AppRequestErrorCode.PARAM_RANGE, "机构对接人长度不能超过50");
        }

        // 机构联系人 机构名称不能为空
        if (StrUtil.isEmpty(param.getInstituteName())) {
            return XmResultJson.fail(AppRequestErrorCode.PARAM_LOST, "机构名称不能为空");
        }

        if (!param.getInstituteName().equals(member.getInstituteName())) {
            // 机构 名称不能重复
            Integer count = memberDao.countByOrgIdAndInstituteNameAndNotEqualStatus(param.getOrgId(), param.getInstituteName(), 4);
            if (count != 0) {
                return XmResultJson.fail(AppRequestErrorCode.PARAM_LOST, "机构名称已存在");
            }
        }
        // 隐藏相似的数据也需要更改
        List<MemberDO> similarlyMembers = getSimilarlyMembers(member.getOrgId(), member.getPhone(),
                member.getEmail(), member.getAliPayUserId(), member.getOpenId(), member.getMemberType(), member.getOutNo());

        ServiceResult<String> checkFieldValueFormatResult = checkFieldValueFormatValid(param.getFieldValues());
        if (!checkFieldValueFormatResult.isSuccess()) {
            return XmResultJson.fail(AppRequestErrorCode.PARAM_LOST, checkFieldValueFormatResult.getMsg());
        }

        // 获取组织信息
        ServiceResult<OrganizationDTO> organization = getOrganization(param.getOrgId());
        if (!organization.isSuccess()) {
            return XmResultJson.fail(-1, organization.getMsg());
        }
        OrganizationDTO dto = organization.getData();
        if (CollectionUtil.isNotEmpty(similarlyMembers)) {
            similarlyMembers.forEach(similarlyMember -> {
                MemberDO updateMember = this.toMemberDoForUpdate(param);
                updateMember.setId(similarlyMember.getId());
                updateMember.setMemberType(MemberTypeEnum.INSTITUTION.getIndex());
                updateMember.setCreateTime(similarlyMember.getCreateTime());
                updateMember.setOrgId(similarlyMember.getOrgId());
                updateMember(updateMember);
                String identityType = "企业对接人";
                String numberId = "000";
                // 推送
                MemberMessage message = MemberUtil.memberDoToMemberMessage(updateMember);
                message.setStatus(similarlyMember.getStatus());
                message.setIdentityType(identityType);
                message.setNumberId(numberId);
                message.setOrgCode(dto.getCode());
                message.setOrgName(dto.getName());
                memberUtil.publishUpdateMember(message);

            });
        }
        return XmResultJson.success(param.getId());
    }

    @Override
    public ServiceResult<Void> saveImportMember(MemberDO member, Integer quota) {
        // 创建联系人
        member = memberDao.importSave(member);

        // 获取组织信息
        ServiceResult<OrganizationDTO> organization = getOrganization(member.getOrgId());
        if (!organization.isSuccess()) {
            return ServiceResult.fail(organization.getMsg());
        }
        OrganizationDTO dto = organization.getData();

        //若 手机或者邮箱是内部联系人
        String identityType = "企业对接人";

        // 推送创建的联系人
        MemberMessage message = MemberUtil.memberDoToMemberMessage(member);
        message.setIdentityType(identityType);
        message.setNumberId("000");
        message.setOrgCode(dto.getCode());
        message.setOrgName(dto.getName());
        memberUtil.publishCreateMember(message);

        // 创建名片
        SourceCardDo card = new SourceCardDo();
        card.setMemberId(member.getId());
        card.setSource(CardSourceTypeEnum.FILE.getIndex());
        card.setOrgId(member.getOrgId());
        String memberNo = member.getMemberNo();

        String cardNo = memberNo + "-" + "000";
        card.setSerial(cardNo);
        card.setData(JSONObject.toJSONString(member));
        sourceCardDao.save(card);

        return ServiceResult.success();
    }


}
